package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.NoticeDTO;
import com.example.dto.NoticeQueryDTO;
import com.example.service.NoticeService;
import com.example.service.UserNoticeReadService;
import com.example.vo.NoticeVO;
import com.example.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/notice")
@CrossOrigin
public class NoticeController {
    
    @Autowired
    private NoticeService noticeService;

    @Autowired
    private UserNoticeReadService userNoticeReadService;

    @Autowired
    private UserContextUtil userContextUtil;
    
    /**
     * 分页查询通知列表
     */
    @PostMapping("/list")
    @RequirePermission("notice:list")
    public Result<PageResult<NoticeVO>> getNoticeList(@RequestBody NoticeQueryDTO queryDTO) {
        PageResult<NoticeVO> result = noticeService.getNoticeList(queryDTO);
        return Result.success(result);
    }
    
    /**
     * 获取通知详情
     */
    @GetMapping("/{id}")
    @RequirePermission("notice:view")
    public Result<NoticeVO> getNoticeById(@PathVariable Long id) {
        NoticeVO notice = noticeService.getNoticeById(id);
        return Result.success(notice);
    }
    
    /**
     * 新增通知
     */
    @PostMapping("/add")
    @RequirePermission("notice:add")
    public Result<Void> addNotice(@RequestBody NoticeDTO noticeDTO) {
        noticeService.addNotice(noticeDTO);
        return Result.success();
    }
    
    /**
     * 编辑通知
     */
    @PutMapping("/update")
    @RequirePermission("notice:update")
    public Result<Void> updateNotice(@RequestBody NoticeDTO noticeDTO) {
        noticeService.updateNotice(noticeDTO);
        return Result.success();
    }
    
    /**
     * 删除通知
     */
    @DeleteMapping("/{id}")
    @RequirePermission("notice:delete")
    public Result<Void> deleteNotice(@PathVariable Long id) {
        noticeService.deleteNotice(id);
        return Result.success();
    }
    
    /**
     * 发布通知
     */
    @PutMapping("/publish/{id}")
    @RequirePermission("notice:publish")
    public Result<Void> publishNotice(@PathVariable Long id) {
        noticeService.publishNotice(id);
        return Result.success();
    }
    
    /**
     * 下线通知
     */
    @PutMapping("/offline/{id}")
    @RequirePermission("notice:offline")
    public Result<Void> offlineNotice(@PathVariable Long id) {
        noticeService.offlineNotice(id);
        return Result.success();
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/mark-read/{id}")
    @RequirePermission("notice:view")
    public Result<Void> markAsRead(@PathVariable Long id) {
        try {
            Long userId = userContextUtil.getCurrentUser().getId();
            boolean success = userNoticeReadService.markAsRead(userId, id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("标记已读失败");
            }
        } catch (Exception e) {
            return Result.error("用户未登录或token无效");
        }
    }

    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread-count")
    @RequirePermission("notice:list")
    public Result<Long> getUnreadCount() {
        try {
            Long userId = userContextUtil.getCurrentUser().getId();
            long count = userNoticeReadService.getUnreadCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("用户未登录或token无效");
        }
    }

    /**
     * 标记所有通知为已读
     */
    @PostMapping("/mark-all-read")
    @RequirePermission("notice:list")
    public Result<Void> markAllAsRead() {
        try {
            Long userId = userContextUtil.getCurrentUser().getId();
            boolean success = userNoticeReadService.markAllAsRead(userId);
            if (success) {
                return Result.success();
            } else {
                return Result.error("标记全部已读失败");
            }
        } catch (Exception e) {
            return Result.error("用户未登录或token无效");
        }
    }

    /**
     * 公开接口：获取已发布的公告列表（供小程序等未登录用户使用）
     */
    @PostMapping("/public/list")
    public Result<PageResult<NoticeVO>> getPublicNoticeList(@RequestBody NoticeQueryDTO queryDTO) {
        // 强制设置状态为已发布
        queryDTO.setStatus(1);
        PageResult<NoticeVO> result = noticeService.getNoticeList(queryDTO);
        return Result.success(result);
    }

    /**
     * 公开接口：获取通知详情（供小程序等未登录用户使用）
     */
    @GetMapping("/public/{id}")
    public Result<NoticeVO> getPublicNoticeById(@PathVariable Long id) {
        try {
            NoticeVO notice = noticeService.getNoticeById(id);
            // 只返回已发布的通知
            if (notice != null && notice.getStatus() == 1) {
                return Result.success(notice);
            } else {
                return Result.error("通知不存在或未发布");
            }
        } catch (Exception e) {
            return Result.error("获取通知详情失败");
        }
    }

}